// pages/bind-tel-code/bind-tel-code.js
var api = require('../../config/api.js');
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputLen: 6,
    iptValue: "",
    isFocus: false,

    snsMsgWait: 60,
    isSendCode: false,
    sendTime: '60s后重发'
  },
  onFocus: function(e) {
    var that = this;
    that.setData({
      isFocus: true
    });
  },
  setValue: function(e) {
    var that = this;
    var strInput = e.detail.value;
    that.setData({
      iptValue: strInput
    });

    if (strInput.length == 6) {
      that.getBindData(strInput);
    }
  },

  //获取验证码
  getCodeData() {
    let that = this;
    util.request(api.SmsCode, {
      mobile: that.data.tel
    }, 'post').then(function(res) {
      if (res.errno == 0) {
        var inter = setInterval(function() {
          that.setData({
            sendTime: that.data.snsMsgWait + 's后重发',
            snsMsgWait: that.data.snsMsgWait - 1,
            isSendCode: false
          });
          if (that.data.snsMsgWait < 0) {
            clearInterval(inter)
            that.setData({
              snsMsgWait: 60,
              isSendCode: true
            });
          }
        }.bind(that), 1000);

      } else {
        util.myToast(res.errmsg)
        setTimeout(function(e) {
          wx.navigateBack({
            delta: 1
          })
        }, 1500)

      }
    });
  },
  //绑定手机
  getBindData(code) {
    let that = this;
    util.request(api.BindPhone, {
      mobile: that.data.tel,
      code: code
    }, 'post').then(function(res) {
      if (res.errno == 0) {
        wx.setStorageSync("token", res.token);
        wx.setStorageSync("users", res.userInfo);
        util.myToast("绑定成功")
        setTimeout(function() {
          wx.navigateBack({
            delta: 2
          })
        }, 1000);

      } else {
        util.myToast(res.errmsg)
      }
    });
  },
  //点击获取验证码
  onGetCode: util.throttle(function(e) {
    this.getCodeData();
  }),

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var tel = options.tel;
    this.setData({
      tel: tel
    })
    this.getCodeData();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})